package com.sayice.coursetable.ui.course.day;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sayice.coursetable.R;
import com.sayice.coursetable.databinding.FragmentDayBinding;
import com.sayice.coursetable.logic.model.Course;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日课程界面
 */
public class DayFragment extends Fragment {
    private FragmentDayBinding binding;
    private DayViewModel viewModel;

    private DayCourseAdapter courseAdapter;

    private Integer initialTableId;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentDayBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d("DayFragment", "onViewCreated");
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(DayViewModel.class);
        viewModel.getCourseLiveData().observe(getViewLifecycleOwner(), courses -> {
            viewModel.courses.clear();
            viewModel.courses.addAll(courses);
            courseAdapter.notifyItemRangeChanged(0, 6);
        });
        if (initialTableId != null) {
            Log.d("DayFragment", "initTable");
            viewModel.updateCourses(initialTableId);
            initialTableId = null;
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.courseList.setLayoutManager(layoutManager);
        courseAdapter = new DayCourseAdapter(viewModel.courses);
        binding.courseList.setAdapter(courseAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    /**
     * 更新课程
     *
     * @param tableId 课表编号
     */
    public void updateCourses(int tableId) {
        if (viewModel == null) {
            initialTableId = tableId;
        } else {
            viewModel.updateCourses(tableId);
        }
    }
}
